/**
 * 内容优化服务
 * 提供AI智能优化建议和自动优化功能
 */

export interface OptimizationRequest {
  content: string;
  optimization_type: 'grammar' | 'style' | 'structure' | 'seo' | 'readability' | 'all';
  target_style?: 'formal' | 'casual' | 'academic' | 'creative' | 'business';
  language?: string;
  preserve_tone?: boolean;
}

export interface OptimizationSuggestion {
  type: string;
  severity: 'info' | 'warning' | 'error';
  position: {
    start: number;
    end: number;
  };
  original: string;
  suggestion: string;
  reason: string;
  confidence: number;
}

export interface OptimizationResponse {
  optimized_content: string;
  suggestions: OptimizationSuggestion[];
  improvements: {
    grammar_fixes: number;
    style_improvements: number;
    structure_changes: number;
    readability_score_before: number;
    readability_score_after: number;
  };
  summary: string;
}

export interface SEOOptimizationRequest {
  content: string;
  keywords: string[];
  target_length?: number;
  meta_description?: boolean;
}

export interface SEOOptimizationResponse {
  optimized_content: string;
  meta_title: string;
  meta_description: string;
  keyword_density: Record<string, number>;
  seo_score: number;
  suggestions: string[];
}

class OptimizationService {
  private baseUrl: string;

  constructor() {
    this.baseUrl = import.meta.env.VITE_API_URL || 'http://localhost:8002/api/v1';
  }

  /**
   * 优化内容
   */
  async optimize(request: OptimizationRequest): Promise<OptimizationResponse> {
    try {
      const response = await fetch(`${this.baseUrl}/optimization/optimize`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.getAuthToken()}`
        },
        body: JSON.stringify(request)
      });

      if (!response.ok) {
        throw new Error(`Optimization failed: ${response.statusText}`);
      }

      return await response.json();
    } catch (error) {
      console.error('Optimization error:', error);
      throw error;
    }
  }

  /**
   * 获取优化建议（不自动修改）
   */
  async getSuggestions(content: string, type: string = 'all'): Promise<OptimizationSuggestion[]> {
    try {
      const response = await fetch(`${this.baseUrl}/optimization/suggestions`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.getAuthToken()}`
        },
        body: JSON.stringify({
          content: content,
          optimization_type: type
        })
      });

      if (!response.ok) {
        throw new Error(`Failed to get suggestions: ${response.statusText}`);
      }

      const result = await response.json();
      return result.suggestions;
    } catch (error) {
      console.error('Get suggestions error:', error);
      return [];
    }
  }

  /**
   * SEO优化
   */
  async optimizeForSEO(request: SEOOptimizationRequest): Promise<SEOOptimizationResponse> {
    try {
      const response = await fetch(`${this.baseUrl}/optimization/seo`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.getAuthToken()}`
        },
        body: JSON.stringify(request)
      });

      if (!response.ok) {
        throw new Error(`SEO optimization failed: ${response.statusText}`);
      }

      return await response.json();
    } catch (error) {
      console.error('SEO optimization error:', error);
      throw error;
    }
  }

  /**
   * 检查语法错误
   */
  async checkGrammar(content: string): Promise<OptimizationSuggestion[]> {
    try {
      const response = await fetch(`${this.baseUrl}/optimization/grammar`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.getAuthToken()}`
        },
        body: JSON.stringify({ content })
      });

      if (!response.ok) {
        throw new Error(`Grammar check failed: ${response.statusText}`);
      }

      const result = await response.json();
      return result.errors;
    } catch (error) {
      console.error('Grammar check error:', error);
      return [];
    }
  }

  /**
   * 改进文章结构
   */
  async improveStructure(content: string): Promise<OptimizationResponse> {
    try {
      const response = await fetch(`${this.baseUrl}/optimization/structure`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.getAuthToken()}`
        },
        body: JSON.stringify({ content })
      });

      if (!response.ok) {
        throw new Error(`Structure improvement failed: ${response.statusText}`);
      }

      return await response.json();
    } catch (error) {
      console.error('Structure improvement error:', error);
      throw error;
    }
  }

  /**
   * 简化内容（提高可读性）
   */
  async simplify(content: string, targetGrade: number = 8): Promise<OptimizationResponse> {
    try {
      const response = await fetch(`${this.baseUrl}/optimization/simplify`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.getAuthToken()}`
        },
        body: JSON.stringify({
          content: content,
          target_reading_level: targetGrade
        })
      });

      if (!response.ok) {
        throw new Error(`Content simplification failed: ${response.statusText}`);
      }

      return await response.json();
    } catch (error) {
      console.error('Simplification error:', error);
      throw error;
    }
  }

  /**
   * 批量优化
   */
  async batchOptimize(contents: string[], type: string = 'all'): Promise<OptimizationResponse[]> {
    try {
      const response = await fetch(`${this.baseUrl}/optimization/batch`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.getAuthToken()}`
        },
        body: JSON.stringify({
          contents: contents,
          optimization_type: type
        })
      });

      if (!response.ok) {
        throw new Error(`Batch optimization failed: ${response.statusText}`);
      }

      const result = await response.json();
      return result.results;
    } catch (error) {
      console.error('Batch optimization error:', error);
      throw error;
    }
  }

  /**
   * 应用单个建议
   */
  applySuggestion(content: string, suggestion: OptimizationSuggestion): string {
    const before = content.substring(0, suggestion.position.start);
    const after = content.substring(suggestion.position.end);
    return before + suggestion.suggestion + after;
  }

  /**
   * 应用多个建议
   */
  applySuggestions(content: string, suggestions: OptimizationSuggestion[]): string {
    // 按位置从后往前排序，避免位置偏移
    const sortedSuggestions = [...suggestions].sort((a, b) => b.position.start - a.position.start);
    
    let result = content;
    for (const suggestion of sortedSuggestions) {
      result = this.applySuggestion(result, suggestion);
    }
    
    return result;
  }

  /**
   * 获取认证令牌
   */
  private getAuthToken(): string {
    return localStorage.getItem('auth_token') || '';
  }
}

export const optimizationService = new OptimizationService();